package lancs.mobilemedia.core.ui.controller.commands;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;

import lancs.mobilemedia.core.ui.controller.AbstractController;
import lancs.mobilemedia.core.ui.controller.ControllerCommand;
import lancs.mobilemedia.core.ui.controller.PhotoController;
import lancs.mobilemedia.core.ui.datamodel.AlbumData;
import lancs.mobilemedia.core.ui.datamodel.ImageData;
import lancs.mobilemedia.lib.exceptions.ImageNotFoundException;
import lancs.mobilemedia.lib.exceptions.NullAlbumDataReference;

public class SetFavorite implements ControllerCommand {

	public boolean execute(AbstractController controller) {
		String selectedImageName = ((PhotoController) controller).getSelectedImageName();
		try {
			ImageData image = controller.getAlbumData().getImageInfo(selectedImageName);
			image.toggleFavorite();
			((PhotoController) controller).updateImage(image);
			System.out.println("<* BaseController.handleCommand() *> Image = "+ selectedImageName + "; Favorite = " + image.isFavorite());
		} catch (ImageNotFoundException e) {
			Alert alert = new Alert("Error", "The selected photo was not found in the mobile device", null, AlertType.ERROR);
			Display.getDisplay(controller.getMidlet()).setCurrent(alert, Display.getDisplay(controller.getMidlet()).getCurrent());
		} catch (NullAlbumDataReference e) {
			controller.setAlbumData(new AlbumData());
			Alert alert = new Alert( "Error", "The operation is not available. Try again later !", null, AlertType.ERROR);
			Display.getDisplay(controller.getMidlet()).setCurrent(alert, Display.getDisplay(controller.getMidlet()).getCurrent());
		}
		return true;
	}
}
